var moment      = require('moment');
var db          = require('../../config/mongo_database');
var secret      = require('../../config/secret');
var redisClient = require('../../config/redis_database').redisClient;

var tokenManager = require('../../config/token_manager');
var logger       = require('../../config/log4js').logger('access');
var property     = require('../../route/property');



// 获取后台订单列表
exports.backlist = function(req, res) {
	var trade = req.body.trade || '';
	var type = req.body.type || '';
	var pages = req.body.pages || 0;
	
	var where = {status:'1'};
	if(trade!='') where.trade = trade;
	if(type!='')  where.type  = type;

	db.orderModel.count(where, function(err, count){
		db.orderModel	
		.where(where)
		.skip(pages*12)
		.limit(12)
		.sort({ updated : -1 })
		.exec(function(err, list){
			res.json({count:count, list:list});
		})
	})
};


// 更新充值记录
exports.charge = function(req, res){
	var id = req.body._id
	var trade = req.body.trade

	db.orderModel.findOne({_id:id, status:'1', trade:'1', type:'0'}, function(err, order){
		if(err) {
			logger.error("未查询到该笔订单[orderModel:{_id:id, status:'1', trade:'1', type:'0'}]", id)
			return res.json({status:500, msg:'未查询到该笔订单'});
		}
		else{
			order.trade = trade
			chargeProperty(order)
			return res.json({status:200, msg:'更新成功'});
		}
	})
}

/**
   1. 确认到账后，进行更新
   2. 首先更新订单，状态改为交易成功
   3. 目标客户对应钱包进行充值
   4. 新增交易记录到对账单
   风险点：如扣款和增款同时发生如何避免？ 另外还有获奖金额？

   人工操作：优先处理此人扣款操作，再处理增款操作

**/
function chargeProperty(order){
	db.orderModel.update({_id:order.id, status:'1', trade:'1'}, {$set:{trade:order.trade, updated:new Date()}}, function(err){
		if(err) 
			logger.error("更新失败db.orderModel.update({_id:order.id, status:'1', trade:'1'}, {$set:{trade:order.trade}}", id, order.trade)
		else
			db.userModel.findOne({_id: order.userid}, function(err, user){
				user.wallet[order.btype].asset = user.wallet[order.btype].asset + order.pay;
				db.userModel.update({_id: order.userid}, {$set:{wallet: user.wallet, updated:new Date()}}, function(err){
					if(err)
						logger.error("更新失败db.userModel.update({_id: order.userid}, {$set:{wallet: user.wallet}}", user.wallet)
					else
						property.addBalance({
											userid:order.userid, 
											username:order.detail.username, 
											btype:order.btype, 
											pay:order.pay
										})
				})
			})
	})
}